/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.client.presenter;

import td.client.ClientState;
import td.client.place.NameTokens;
import td.client.presenter.handlers.DetailUiHandlers;
import td.client.presenter.handlers.DetailUiHandlers.MyView;
import td.domain.DemoStore;
import td.domain.Thought;
import td.domain.Topic;
import td.pt.RightNavigationPresenter;
import td.pt.event.HideAllPopupsEvent;
import td.pt.event.TagAThoughtEvent;
import td.pt.event.TagAThoughtEvent.TagAThoughtHandler;
import td.pt.event.ThoughtListingEvent;
import td.pt.event.UseReferenceNavigationEvent;
import td.pt.event.UseReferenceNavigationEvent.ReferenceNavigationType;
import td.pt.event.ViewTagsOnThoughtEvent;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

/**
 * @author Artem Shamsutdinov
 * 
 */
public class DetailPresenter extends Presenter<MyView, DetailPresenter.MyProxy>
		implements DetailUiHandlers {

	@Inject
	PlaceManager placeManager;

	String name;
	Long thoughtId;

	@Inject
	ClientState state;

	@Inject
	RightNavigationPresenter rightNavPresenter;

	@ProxyCodeSplit
	@NameToken(NameTokens.detail)
	public interface MyProxy extends ProxyPlace<DetailPresenter> {
	}

	TagAThoughtHandler tagAThoughtHandler = new TagAThoughtHandler() {

		@Override
		public void onTagAThought(TagAThoughtEvent event) {
			getView().getTags()
					.setText(
							"Tags: "
									+ state.getCurrentThought()
											.getAppliedTags().size());
			getView().getTags().setEnabled(true);
		}
	};

	@Inject
	public DetailPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy) {
		super(eventBus, view, proxy);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, RootPresenter.SLOT_content, this);
	}

	@Override
	public void prepareFromRequest(final PlaceRequest request) {
		super.prepareFromRequest(request);
		name = request.getParameter(DetailUiHandlers.NAME,
				DetailUiHandlers.DEFAULT_NAME);

		try {
			thoughtId = Long.parseLong(name);
		} catch (NumberFormatException nfe) {
			Window.alert("Unknown thought!");
		}
		HideAllPopupsEvent hideAllPopupsEvent = new HideAllPopupsEvent();
		getEventBus().fireEvent(hideAllPopupsEvent);
		loadThought();
	}

	@Override
	protected void onBind() {
		super.onBind();
		registerHandler(getEventBus().addHandler(TagAThoughtEvent.TYPE,
				tagAThoughtHandler));
		getView().getTags().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				ViewTagsOnThoughtEvent viewTagsOnThoughtEvent = new ViewTagsOnThoughtEvent(
						state.getCurrentThought(), DetailPresenter.this);
				getEventBus().fireEvent(viewTagsOnThoughtEvent);
			}
		});
		getView().getReferencedBy().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				UseReferenceNavigationEvent useReferenceNavigationEvent = new UseReferenceNavigationEvent(
						ReferenceNavigationType.VIEW_REFERENCES_OF_THOUGHT,
						state.getCurrentThought(), DetailPresenter.this);
				getEventBus().fireEvent(useReferenceNavigationEvent);
			}
		});
		getView().getReferences().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				UseReferenceNavigationEvent useReferenceNavigationEvent = new UseReferenceNavigationEvent(
						ReferenceNavigationType.VIEW_REFERENCED_BY_THOUGHT,
						state.getCurrentThought(), DetailPresenter.this);
				getEventBus().fireEvent(useReferenceNavigationEvent);
			}
		});
	}

	@Override
	protected void onReset() {
		super.onReset();
	}

	private void loadThought() {
		state.setCurrentPlace(NameTokens.getDetail());
		Thought thought = DemoStore.db().getThought(thoughtId);

		// FIXME: hack for the demo
		if (thought == null) {
			thought = DemoStore.db().rootCategory.getThoughts().get(0);
		}
		if (thought != null) {
			getView().getTitle().setText(thought.getTitle());
			getView().getThinker().setText(thought.getThinker().getThinkerId());
			getView().getThinker().setTargetHistoryToken(
					NameTokens.thinker + ";name="
							+ thought.getThinker().getId());
			getView().getSynopsis().setText(thought.getSynopsis());
			getView().getThoughtBody().setText(thought.getText());

			rightNavPresenter.determineReferenceStatus(thought);

			Topic topic = thought.getTopic();
			if (topic != null) {
				getView().getTopic().setText(topic.getName());
			}
			state.setCurrentThought(thought);
			{
				int numTags = 0;
				if (thought.getAppliedTags() != null) {
					numTags = thought.getAppliedTags().size();
				}
				getView().getTags().setEnabled(numTags > 0);
				getView().getTags().setText("Tags: " + numTags);
			}
			{
				int numReferencedThoughts = 0;
				if (thought.getReferencedThoughts() != null) {
					numReferencedThoughts = thought.getReferencedThoughts()
							.size();
				}
				getView().getReferences().setEnabled(numReferencedThoughts > 0);
				getView().getReferences().setText(
						"References: " + numReferencedThoughts);
			}
			{
				int numReferencingThoughts = 0;
				if (thought.getReferencingThoughts() != null) {
					numReferencingThoughts = thought.getReferencingThoughts()
							.size();
				}
				getView().getReferencedBy().setEnabled(
						numReferencingThoughts > 0);
				getView().getReferencedBy().setText(
						"Referenced By: " + numReferencingThoughts);
			}
		} else {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			ThoughtListingEvent listingEvent = new ThoughtListingEvent(
					"Most Read Thoughts across all Categories",
					DemoStore.db().rootCategory);
			getEventBus().fireEvent(listingEvent);
		}

		rightNavPresenter.getView().getAddAReference().setVisible(false);
		rightNavPresenter.getView().getCategorize().setVisible(false);
		rightNavPresenter.getView().getPublish().setVisible(false);
	}

	@Override
	public void edit(String title) {
		// FIXME: once the prototype is integrated
		// PlaceRequest request = new PlaceRequest(NameTokens.edit).with(
		// DetailUiHandlers.NAME, title);
		// placeManager.revealPlace(request);
	}
}
